package com.wewoo.log4e.core.Register;

import com.alibaba.fastjson.JSON;
import com.wewoo.log4e.core.LogTemplate;
import com.wewoo.log4e.core.util.ReadLogUtil;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ReadRegister
 * @Description TODO
 * @Author tangjin
 * @Date 10:49 2022/2/22
 **/
@RequiredArgsConstructor
public class ReadRegister implements InitializingBean, ApplicationContextAware {
    public static final Logger LOGGER = LoggerFactory.getLogger(ReadRegister.class);
    private final List<ReadLogUtil> readLogUtils;
    private Map<Class<? extends ReadLogUtil>, ReadLogUtil> readLogUtilMap = new HashMap<>();
    private Map<String, ReadLogUtil> readLogUtilContext = new HashMap<>();
    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        LOGGER.info("init read util arrays - {}", JSON.toJSONString(readLogUtils));
        Map<String, ReadLogUtil> beanMap = applicationContext.getBeansOfType(ReadLogUtil.class);
        String name = null;
        for (ReadLogUtil readLogUtil : beanMap.values()) {
            name = readLogUtil.getClass().getSimpleName();
            //将类名作为 key,
            readLogUtilContext.put(name, readLogUtil);
            readLogUtilMap.put(readLogUtil.getClass(),readLogUtil);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    public ReadLogUtil switchRead(String name) {
        return readLogUtilContext.get(name);
    }
}
